package pt.mauromad.guias.utils.transformation;

import static pt.mauromad.guias.utils.CastUtils.cast;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public abstract class Transformation<S, T> {
	public <R extends Collection<T>> R get(Collection<S> collection) {
		if (collection == null)
			return null;

		Collection<T> result;
		try {
			if (collection.getClass().getName().contains("org.hibernate"))
				throw new Exception();
			result = cast(collection.getClass().newInstance());
		} catch (Exception e) {
			if (List.class.isInstance(collection))
				result = new ArrayList<>();
			else if (Set.class.isInstance(collection)) {
				result = new HashSet<>();
			} else
				result = new ArrayList<>();
		}

		for (S obj : collection)
			result.add(getSafe(obj));

		return cast(result);
	}

	public final T get(S obj) {
		return obj == null ? null : getSafe(obj);
	}

	public abstract T getSafe(S obj);
}
